#include "snake.h"
//内存操作
// 释放 Player 结构体的内存
void free_player(Player *player) {
    if (!player) return;

    // 释放 Player 内部动态分配的内容
    if (player->snake.body) {
        free(player->snake.body);
    }

    // 如果 Player 里有 uthash 管理的哈希链表，调用相应的释放函数（示例）：
    // HASH_CLEAR(hh, player->someHashField);

    // 最后释放 player 自身
    free(player);
}
// 释放 Snake（身体是动态数组）
void free_snake(Snake *snake) {
    if (!snake) return;
    if (snake->body) {
        free(snake->body);
        snake->body = NULL;
    }
    snake->length = 0;
}


// 释放 Packet
void snake_free_packet(Packet *packet) {
    if (!packet) return;

    switch (packet->type) {
        case PACKET_TYPE_INIT:
            if (packet->init.me) {
                free_player(packet->init.me);
                packet->init.me = NULL;
            }
            break;

        case PACKET_TYPE_SYNC:
            if (packet->sync.me) {
                free_player(packet->sync.me);
                packet->sync.me = NULL;
            }
            if (packet->sync.players) {
                for (int i = 0; i < packet->sync.playersCount; ++i) {
                    if (packet->sync.players[i]) {
                        free_player(packet->sync.players[i]);
                        packet->sync.players[i] = NULL;
                    }
                }
                free(packet->sync.players);
                packet->sync.players = NULL;
            }
            break;

        case PACKET_TYPE_FRAME:
            if (packet->frame.frames) {
                for (int i = 0; i < packet->frame.frameCount; ++i) {
                    if (packet->frame.frames[i].type == PACKET_TYPE_JOIN &&
                        packet->frame.frames[i].snake.body) {
                        free(packet->frame.frames[i].snake.body);
                        packet->frame.frames[i].snake.body = NULL;
                        }
                }
                free(packet->frame.frames);
                packet->frame.frames = NULL;
            }
            break;

        default:
            break;
    }

    free(packet);
}
